$(function(){

    ajaxOrderContent(0,0);  // 页面加载订单详细信息

    $('.form-wrap').on('click','.new-area',function(e){ //选择区域
        var region = $(this).parents('.form-wrap').siblings('.newconfirm-region');
        region.show();
        $(this).parents('.form-wrap').addClass('out');
        ajaxRegion(1,0,region);
        e.preventDefault();
    })

    $('.newconfirm-region').on('click','.btn-close',function(e){ // 地址的关闭
        $(this).parents('.newconfirm-region').hide();
        $(this).parents('.newconfirm-region').siblings('.form-wrap').removeClass('out');
        e.preventDefault();
    })

    $('.address-list').on('click','.add-button',function(e){ //地址添加的时候
        $('#address-add-actions').modal('open');
        $('#address-list-actions').modal('close');
    })

    $('.address-list').on('click','.address-edit',function(e){ //地址编辑的时候
        var address_id = $(this).attr('address-id');
        $.ajax({
            type: 'post',
            async: false,
            dataType : 'json',
            url: hostUrl()+'address/editAddress',
            data: {address_id:address_id},
            success: function(json) {
                if (json.status) {
                    $('#address-edit-actions .address-edit').html(json.messages);
                    $('#address-list-actions').modal('close');
                    $('#address-edit-actions').modal('open');
                } else {
                    alertMessage(json.messages);
                }
            }
        });
    })

    $('#address-add-actions').on('click','.btn-close',function(e){  //添加收货地址的时候 关闭按钮
           $('#address-add-actions').modal('close');
           $('#address-list-actions').modal('open');
    })

    $('#address-edit-actions').on('click','.btn-close',function(e){  //编辑收货地址的时候 关闭按钮
           $('#address-edit-actions').modal('close');
           $('#address-list-actions').modal('open');
    })

    $('.form-wrap').on('click','.set-default-address',function(e){ //设为默认地址--编辑

        var checkBox = $(this).find('.check-wrapper');
        if(checkBox.hasClass('active')){
            checkBox.removeClass('active');
            $(this).find('.is_default').attr('value',1);
        }else{
            checkBox.addClass('active');
            $(this).find('.is_default').attr('value',2);
        }
        e.preventDefault();
    })

    $('.address-container').on('click','.address-set',function(e){ //选择地址

        var address_id = $(this).attr('address-id');
        var swim = $('input[name=swim]').val();
        ajaxOrderContent(address_id,swim);
        $(this).find('.check-wrapper').addClass('active');
        $(this).parent('li').siblings().find('.check-wrapper').removeClass('active');
        $('#address-list-actions').modal('close');
        e.preventDefault();
    })


    $('.newconfirm-address-form').on('submit','.address-add',function(e){ //地址的添加 和 修改

        e.preventDefault();
        var receiver_name = $('.address-add input[name="receiver_name"]').val();
        var tel = $('.address-add input[name="tel"]').val();
        var code = $('.address-add input[name="code"]').val();
        var province_name = $('.address-add input[name="province_name"]').val();
        var detailed = $('.address-add input[name="detailed"]').val();
        var telT = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        var codeT = /^[0-9]{6}$/;
        if (receiver_name.length==0) {
            errorMessages('请填写姓名');
            return false;
        }
        if (tel.length==0){
            errorMessages('请填写手机号码');
            return false;
        }
        if (!telT.test(tel)){
            errorMessages('请填写正确的手机号码');
            return false;
        }
        if (code.length==0){
            errorMessages('请填写邮政编码');
            return false;
        }
        if (!codeT.test(code)){
            errorMessages('请填写正确的邮政编码');
            return false;
        }
        if (province_name.length==0){
            errorMessages('请填写地址');
            return false;
        }
        if (detailed.length==0){
            errorMessages('请填写详细地址');
            return false;
        }
        $.ajax({
            type: 'post',
            async: false,
            dataType : 'json',
            url: hostUrl()+'address/insertAddress',
            data: $('.address-add').serialize(),
            beforeSend: function() {
                $('.address-add button[type=submit]').text('正在保存').attr('disabled', true);
            },
            success: function(json) {
                if (json.status) {
                    $('.address-list ul').html(json.messages);
                    $('#address-add-actions').modal('close');
                } else {
                    errorMessages(json.messages);
                }
                $('#address-list-actions').modal('open');
                $('.address-add button[type=submit]').text('保存').removeAttr('disabled');
            }
        });
        return false;
    })


    $('.edit-address-form').on('submit','.address-edit',function(e){ //地址的添加 和 修改

        e.preventDefault();
        e.stopPropagation();
        var receiver_name = $('.address-edit input[name="receiver_name"]').val();
        var tel = $('.address-edit input[name="tel"]').val();
        var code = $('.address-edit input[name="code"]').val();
        var province_name = $('.address-edit input[name="province_name"]').val();
        var detailed = $('.address-edit input[name="detailed"]').val();
        var telT = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        var codeT = /^[0-9]{6}$/;
        if (receiver_name.length==0) {
            errorMessages('请填写姓名');
            return false;
        }
        if (tel.length==0){
            errorMessages('请填写手机号码');
            return false;
        }
        if (!telT.test(tel)){
            errorMessages('请填写正确的手机号码');
            return false;
        }
        if (code.length==0){
            errorMessages('请填写邮政编码');
            return false;
        }
        if (!codeT.test(code)){
            errorMessages('请填写正确的邮政编码');
            return false;
        }
        if (province_name.length==0){
            errorMessages('请填写地址');
            return false;
        }
        if (detailed.length==0){
            errorMessages('请填写详细地址');
            return false;
        }
        $.ajax({
            type: 'post',
            async: false,
            dataType : 'json',
            url: hostUrl()+'address/insertAddress',
            data: $('.address-edit').serialize(),
            beforeSend: function() {
                $('.address-edit button[type=submit]').text('正在保存').attr('disabled', true);
            },
            success: function(json) {
                if (json.status) {
                    $('.address-list ul').html(json.messages);
                    $('#address-edit-actions').modal('close');
                } else {
                    errorMessages(json.messages);
                }
                $('#address-list-actions').modal('open');
                $('.address-edit button[type=submit]').text('保存').removeAttr('disabled');
            }
        });
        return false;
    })

    $('.newconfirm-region  ul').on('click', 'li', function(e){//地址选取

        var _this = $(this);
        var type = _this.data('type');
        var text = _this.text();
        var id = _this.data('id');
        var parent = _this.parents('.newconfirm-region');
        var brother = _this.parents('.newconfirm-region').siblings('.form-wrap');
        var addressWare = parent.find('#addressWare');
        if(type == 1){
            addressWare.attr('data-province-id',id);
            addressWare.attr('data-province-name',text);
            ajaxRegion(id,type,parent);
        }else if(type == 2){
            addressWare.attr('data-city-id',id);
            addressWare.attr('data-city-name',text);
            ajaxRegion(id,type,parent);
        }else if(type == 3){
            brother.find('input[name=province_id]').val(addressWare.attr('data-province-id'));
            brother.find('input[name=province_name]').val(addressWare.attr('data-province-name'));
            brother.find('input[name=city_id]').val(addressWare.attr('data-city-id'));
            brother.find('input[name=city_name]').val(addressWare.attr('data-city-name'));
            brother.find('input[name=district_id]').val(id);
            brother.find('input[name=district_name]').val(text);
            brother.find('.new-area').html(addressWare.attr('data-province-name')+addressWare.attr('data-city-name')+text+'<i class="iconfont ico-right">&#xe61f;</i>');
            brother.removeClass('out');
            parent.hide();
        }
        e.preventDefault();
    });

    $('#address-edit-actions').on('click','.del',function(){ //删除收货地址

        var address_id = $(this).attr('address-id');
        var swim = $('input[name=swim]').val();
        var chose_address_id = $('input[name=address_id]').val();
        var nconfirm = layer.open({
            type: 1, //1代表页面层
            content: '<div class="content"><div class="title">确定要删除该收货地址吗？</div></div><div class="con-body am-cf"><a class="am-btn closediy">取消</a><a class="am-btn closediy">确定</a></div>',
            style: 'max-width:14.29em;padding:0.714em;border-radius:0.25em',
            shadeClose:false,
            success:function(olayer){
                var cla = 'getElementsByClassName';
                olayer[cla]('closediy')[0].onclick = function(){
                    layer.close(nconfirm);
                }
                olayer[cla]('closediy')[1].onclick = function(){
                    layer.close(nconfirm);
                    $.ajax({
                         type: 'post',
                         async: false,
                         url: hostUrl() + 'address/delete',
                         data: {'address_id': address_id},
                         dataType: 'json',
                         success: function (json) {
                              if (json.status) {
                                 $('.address-list ul').html(json.messages);
                                 $('#address-edit-actions').modal('close');
                                 if( chose_address_id==address_id ){
                                     ajaxOrderContent(0,swim);
                                 }
                             } else {
                                 errorMessages(json.messages);
                             }
                             $('#address-list-actions').modal('open');
                         }
                    })
                }
            }
        })
    });
    $('form.order-infor').on('submit',function(e){  // 订单表的提交
       e.preventDefault();
       $.ajax({
            type: 'post',
            async: false,
            dataType : 'json',
            url: hostUrl()+'order/submit',
            data: $('.order-infor').serialize(),
            beforeSend: function() {
                $('.order-infor button[type=submit]').text('结算中').attr('disabled', true);
            },
            success: function(json) {
                if (json.status) {
                   window.location.href = json.messages;
                } else {
                     alertMessage(json.messages);
                     $('.order-infor button[type=submit]').text('结算').removeAttr('disabled');
                }

            }
       });
       return false;
    })
});

 /**
 * 加载城市
 * @param id
 * @param type
 */
function ajaxRegion(id,type,region) {
    type = parseInt(type) + 1;
    $.ajax({
        type: 'post',
        async: false,
        url: hostUrl() + 'address/ajaxRegion',
        data: {'id': id, 'type': type},
        dataType: 'json',
        success: function (json) {
            region.find('#region-list').html(json.html);
        }
    })
}

/**
 *刚开始载入页面
*/
function ajaxOrderContent(address_id, swim)
{
    $.ajax({
        type: 'post',
        async: false,
        url: hostUrl() + 'order/ajaxOrderContent',
        data: {'address_id':address_id,'swim':swim},
        dataType: 'json',
        success: function (json) {
            if (json.status){
                $('.order-infor').html(json.messages);
                $('img.lazy').lazyload({effect :"fadeIn",threshold :200 });
            } else {
                window.location.href=json.messages;
            }
        }
    })
}

 /**
 * 弹窗消息
 * @param $message
 */
function errorMessages($message)
 {
    $('.bz-alert .alert-content').text($message);
    $('.bz-alert').show();
    setTimeout(function(){
        $('.bz-alert').hide();
    }, 1000);
    return false;
}
